<?php

namespace app\modules\api\controllers;


use app\models\ApiException;
use app\models\Package;
use app\models\Card;
use Yii;
/**
 * 对外公开的接口
 * Class PublicController
 * @package app\modules\api\controllers
 */
class CertController extends BasePublicController
{
    /**
     * 查询本地是否认证
     * @return array
     */
    public function actionIndex()
    {

        $iccid = $this->get('iccid');
        $str = substr($iccid, 0,19);
        $pack = Card::find()->andWhere(['like','iccid',$str])->one();
        //is_cert 是否认证：1：已认证 2：未认证 3：待认证
        if($pack){
            $isCert = $pack['is_cert'];
            $id = $pack['id'];
            if($isCert==3 || $isCert==2 || $isCert='null' || $isCert ='' || empty($isCert)){
                $url = 'http://cu.mangcaoiot.com/api/membership/real-name-status-querymy?iccid='.$iccid;
                $urlData = json_decode($this->actionGetUrl($url),True);
                if($urlData['status']==51){
                    $urlData = json_decode($this->actionGetUrl($url),True);
                    if($urlData['status']==51){
                        $urlData = json_decode($this->actionGetUrl($url),True);
                    }
                }
                if($urlData['data']['rspcode']=="0001"){
                    $status = 1;
                }elseif($urlData['data']['rspcode']=="0000"){
                    $status = 2;
                }
                if($status==1){
                    //更改卡认证状态
                    $connection  = Yii::$app->db;
                    $resUpdate = $connection->createCommand()->update('card',['is_cert'=>$status],
                        ['id'=>$id]
                    )->execute();
                    /*if($resUpdate){
                        return [
                            'code'=>  "1",
                            'msg'=>  '操作成功',
                            'data'=>  [
                                'is_cert'=>$status
                            ]
                        ];
                        exit;
                    }else{
                        return [
                            'code'=>  "1001",
                            'msg'=>  '操作失败',
                            'data'=>  ''
                        ];
                        exit;
                    }*/
                    return [
                            'code'=>  "1",
                            'msg'=>  '操作成功',
                            'data'=>  [
                                'is_cert'=>$status
                            ]
                        ];
                        exit;
                }
                if($isCert==3){
                    $connection  = Yii::$app->db;
                    $resUpdate = $connection->createCommand()->update('card',['is_cert'=>$status],
                        ['id'=>$id]
                    )->execute();
                    if($resUpdate){
                        return [
                            'code'=>  "1",
                            'msg'=>  '操作成功',
                            'data'=>  [
                                'is_cert'=>$status
                            ]
                        ];
                        exit;
                    }else{
                        return [
                            'code'=>  "1002",
                            'msg'=>  '操作失败',
                            'data'=>  ''
                        ];
                        exit;
                    }
                }
                $pack['is_cert'] =$status;
            }
            $data['code'] = "1";
            $data['data']['is_cert']=$pack['is_cert'];
            $data['msg']='操作成功';
        }else{
            $data['code'] = "1001";
            $data['data']['is_cert']="";
            $data['msg']='未查询到卡信息';
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'data'=>  $data['data']
        ];

    }
    /**
     * get curl
     * @param $url
     * @return mixed
     */
    public function actionGetUrl($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);;
        return $tmpInfo;    //返回json对象
        //exit;
    }
    public function actionChaxun()
    {
        $type = $this->get('type');
        $isp = $this->get('isp');
        
        $iccid = $this->get('iccid');
        $pack = Card::findOne(['iccid' => $iccid]);

       
        if($type == '1'){
            $type_name = '30天叠加包';
        }else{
            $type_name = '90天叠加包';
        }
        $res = (new \yii\db\Query())
        ->select(['any_value(package.id) as id','any_value(package.name) as name','any_value(package.data) as data','any_value(package.price) as price','any_value(agent_package.sale_price) as sale_price'])
        ->from('package')
        ->join('join','agent_package','agent_package.package_id=package.id')
        ->andWhere(['agent_package.agent_id'=> $pack['agent_id']])
        ->andFilterWhere(['package.type'=>$type])  
        ->andFilterWhere(['package.isp'=>$isp])
        ->groupBy('agent_package.package_id')
        ->all();
        foreach($res as $key=>$val){
            $res[$key]['id'] = $res[$key]['id'];
            $res[$key]['type_name']=$type_name;
            $res[$key]['data']=floatval($res[$key]['data']);
            $res[$key]['price']=floatval($res[$key]['price']);
            $res[$key]['sale_price'] = floatval($res[$key]['sale_price']);
            

        }

        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }elseif(empty($res)){
            $data['code']="1001";
            $data['msg'] ="未查询到卡";
            $data['data'] = "";
        }
        else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
          'code'=>  $data['code'],
          'msg'=>  $data['msg'],
          'datas'=>  $data['data']
        ];
        //return json_encode($data,JSON_UNESCAPED_SLASHES);
    }
    /**
     * 查询套餐
     *
     */
    public function actionGetpackage(){
        $package_id = $this->get('package_id');
        if(empty($package_id)){
            //$where=' and id='.$package_id;
        }else{
            $connection  = Yii::$app->db;
            $sql     = "select * from package where status=1 and id='".$package_id."' limit 1";
            $command = $connection->createCommand($sql);
            $selectIccid     = $command->queryOne();
            if(empty($selectIccid)){
                return[
                    'code'=>  1002,
                    'msg'=>  '未查询到数据',
                    'datas'=>  ''
                ];
                exit;
            }else{
                return[
                    'code'=>  1,
                    'msg'=>  '操作成功',
                    'datas'=>  $selectIccid
                ];
                exit;
            }
        }

    }
    /**
     * 创建订单（创建用户支付记录）
     *
     */
    public function actionCreateorder(){
        $iccid      = trim($_GET['iccid']);
        $packageid  = trim($_GET['packageid']);
        /*$money      = trim($_GET['money']);*/
        //if(empty($iccid) || empty($packageid) || empty($money)){
        if(!isset($iccid)){
            return[
                'code'=>  1001,
                'msg'=>  '参数不全',
                'datas'=>  ''
            ];
            exit;
        }
        //查询套餐详情
        $connection  = Yii::$app->db;
        $sql     = "select * from package where status=1 and packageid='".$packageid."' limit 1";
        $command = $connection->createCommand($sql);
        $selectIccid     = $command->queryOne();
        if(empty($selectIccid)){
            return[
                'code'=>  1002,
                'msg'=>  '未查询到数据',
                'datas'=>  ''
            ];
            exit;
        }
        //生成 用户订单
        $trade_no =date('YmdHis',time()).rand(1000, 9999);
        $res = $connection->createCommand()->insert('user_card_recharge',['iccid'=>$iccid,
            'packageid'=>$packageid,
            'money'=>$selectIccid['price'],
            'create_time'=>time(),
            'trade_no'=>$trade_no,
            'price'=>$selectIccid['isp_price'],
            'status'=>0,
            'uid'=>'1',
            'card_id'=>'39802',
            'term_length'=>'1',
            'term_length_unit'=>'1',
        ])->execute();
        //查出订单详情
        $idSql ="select * from user_card_recharge where status=0 and trade_no=".$trade_no;
        $res = $connection->createCommand($idSql)->queryOne();
        $session = \Yii::$app->session;
        $session->set("trade_no",$res['trade_no']);
        $session->set("order_id",$res['id']);
        //session('trade_no',$res['trade_no']);
        //session('order_id',$res['id']);
        //Yii::$app->session->addFlash('success', '数据已保存。');
        print_r($res);
        if($res){
            $data['code']="1";
            $data['msg']="操作成功";
            $data['data']=$res;
        }else{
            $data['code']="0";
            $data['msg']="操作失败";
            $data['data']="";
        }
        return [
            'code'=>  $data['code'],
            'msg'=>  $data['msg'],
            'data'=>  $data['data']
        ];
        exit;
    }
    /***
     * 支付成功回调（修改支付状态为已支付）
     */
    public function actionNotify(){
        $session = \Yii::$app->session;
        $order_id = $session['order_id'];
        if(empty($order_id)){
            return[
                'code'=>  1003,
                'msg'=>  '未获取到order_id',
                'datas'=>  ''
            ];
            exit;
        }
        $connection  = Yii::$app->db;
        $idSql ="select * from user_card_recharge where id=".$order_id;
        $res = $connection->createCommand($idSql)->queryOne();
        if($res['status']==1){
            return [
                'code'=>  1004,
                'msg'=>  '已经支付过了',
                'data'=>  ''
            ];
            exit;
        }
        $resUpdate = $connection->createCommand()->update('user_card_recharge',['status'=>'1',
            'pay_time'=>time()
        ],['id'=>$order_id]
        )->execute();
        if($resUpdate){
            return [
                'code'=>  1,
                'msg'=>  '操作成功',
                'data'=>  $resUpdate
            ];
            exit;
        }else{
            return [
                'code'=>  1001,
                'msg'=>  '操作失败',
                'data'=>  ''
            ];
            exit;
        }
    }
    /**
     * 返回数据
     */
    public function backData($code,$res='',$msg='操作成功'){
        if($code==1){
            $data['code']=$code;
            $data['msg']=$msg;
            $data['data']=$res;
            return $data;
            exit;
        }else{
            $data['code']=$code;
            $data['msg']=$msg;
            $data['data']=$res;
            return $data;
            exit;
        }
    }

}
